package cn.iocoder.yudao.module.wms.service.stockdetail;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import cn.iocoder.yudao.module.wms.controller.admin.stockdetail.vo.*;
import cn.iocoder.yudao.module.wms.dal.dataobject.stockdetail.StockDetailDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wms.dal.mysql.stockdetail.StockDetailMapper;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wms.enums.ErrorCodeConstants.*;

/**
 * 库存明细 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class StockDetailServiceImpl implements StockDetailService {

    @Resource
    private StockDetailMapper stockDetailMapper;

    @Override
    public Long createStockDetail(StockDetailSaveReqVO createReqVO) {
        // 插入
        StockDetailDO stockDetail = BeanUtils.toBean(createReqVO, StockDetailDO.class);
        stockDetailMapper.insert(stockDetail);
        // 返回
        return stockDetail.getId();
    }

    @Override
    public void updateStockDetail(Long id, BigDecimal qty) {
        stockDetailMapper.updateStockDetail(id, qty);
    }

    @Override
    public void updateStockDetail(StockDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateStockDetailExists(updateReqVO.getId());
        // 更新
        StockDetailDO updateObj = BeanUtils.toBean(updateReqVO, StockDetailDO.class);
        stockDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteStockDetail(Long id) {
        // 校验存在
        validateStockDetailExists(id);
        // 删除
        stockDetailMapper.deleteById(id);
    }

    private void validateStockDetailExists(Long id) {
        if (stockDetailMapper.selectById(id) == null) {
            throw exception(STOCK_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public StockDetailDO getStockDetail(Long id) {
        return stockDetailMapper.selectById(id);
    }

    @Override
    public PageResult<StockDetailDO> getStockDetailPage(StockDetailPageReqVO pageReqVO) {
        return stockDetailMapper.selectPage(pageReqVO);
    }

    @Override
    public List<StockDetailDO> getStockDetailByProductWarehousePosition(Long productId, Long warehouseId, Long positionId) {
        return stockDetailMapper.selectList(productId, warehouseId, positionId);
    }

    @Override
    public List<StockDetailDO> getStockDetailByDocCode(Long docId, String docCode) {
        return stockDetailMapper.selectList(docId, docCode);
    }

}